
package com.yesep.learn.mqtt.server.auth;

import java.security.interfaces.RSAPrivateKey;

import org.springframework.stereotype.Service;

import com.yesep.learn.mqtt.server.common.auth.IAuthService;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;

/**
 * @Description: 用户名和密码认证服务
 */
@Service
public class AuthService implements IAuthService {

	private RSA rsa;

	public AuthService() {
		this.init();
	}

	/**
	 * 私钥初始化
	 */
	public void init() {
		RSAPrivateKey privateKey = IoUtil.readObj(AuthService.class.getClassLoader().getResourceAsStream("keystore/auth-private.key"));
		this.rsa = new RSA(privateKey, null);
	}

	@Override
	public boolean valid(String username, String password) {
		if (StrUtil.isBlank(username))
			return false;
		if (StrUtil.isBlank(password))
			return false;

		String value = rsa.encryptBcd(username, KeyType.PrivateKey);
		return value.equals(password) ? true : false;
	}
}
